package utils

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

// 从文件中加载 key
func LoadKey(appid string, filePath string) (string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		parts := strings.SplitN(line, ":", 3)
		if len(parts) == 3 && parts[0] == appid {
			return parts[1], nil
		}
	}

	if err := scanner.Err(); err != nil {
		return "", err
	}

	return "", fmt.Errorf("appid %s not found in file", appid)
}

// 从文件中加载 key
func LoadKeys(filePath string) ([][]string, error) {
	result := make([][]string, 0)
	file, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		parts := strings.SplitN(line, ":", 3)
		if len(parts) == 3 {
			result = append(result, parts)
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return result, nil
}
